var express = require('express');
var router = express.Router();
const UserModel = require("../../models/UserModel")
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const {secret} = require('../../config/config')
/* GET home page. */

router.post('/login', (req, res, next) => {
    //表单验证
    if (!(req.body.username && req.body.password)) {
        res.json({
            code: "2000",
            msg: "账号或密码缺失",
            data: null
        })
        return
    }

    UserModel.findOne({ ...req.body, password: md5(req.body.password) })
        .then(data => {
            if (data) {
                //expiresIn 是token存在的有效期
                let token=jwt.sign({ username: data.username, _id: data._id }, secret, { expiresIn: 60 * 60 * 24 * 7 })
                res.json({
                    code:"0",
                    msg:'登录成功',
                    data:token
                })

            } else {
                res.json({
                    code: '2001',
                    msg: "账号或密码错误",
                    data: null
                })
            }
        })
        .catch(error => {
            res.json({
                code: "2002",
                msg: "服务器错误",
                data: null
            })
        })
})



module.exports = router;
